<template>
  <div class="health-reminder-container">
    <h2 class="health-reminder-title">健康数据提醒</h2>
    
    <div class="button-container">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 添加提醒
      </el-button>
    </div>
    
    <el-table
      v-loading="loading"
      :data="reminders"
      style="width: 100%; margin-top: 15px"
      border>
      <el-table-column
        prop="typeName"
        label="项目"
        width="120">
      </el-table-column>
      <el-table-column
        prop="reminderTime"
        label="提醒时间"
        width="100">
      </el-table-column>
      <el-table-column
        label="提醒频率"
        width="120">
        <template #default="scope">
          <span>{{ formatFrequency(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        width="80">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isActive"
            @change="(val) => handleStatusChange(scope.row, val)"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="150">
        <template #default="scope">
          <el-button
            size="small" 
            type="primary"
            @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button
            size="small" 
            type="danger"
            @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-empty 
      description="暂无健康提醒" 
      v-if="reminders.length === 0 && !loading">
      <el-button type="primary" @click="handleAdd">添加提醒</el-button>
    </el-empty>

    <!-- 添加/编辑提醒对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="500px">
      <el-form 
        :model="form" 
        label-width="120px" 
        :rules="rules" 
        ref="formRef">
        <el-form-item label="健康类型" prop="typeId">
          <el-select 
            v-model="form.typeId" 
            placeholder="请选择健康数据类型"
            style="width: 100%">
            <el-option
              v-for="type in healthTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="提醒时间" prop="reminderTime">
          <el-time-picker
            v-model="form.reminderTime"
            placeholder="选择时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            style="width: 100%">
          </el-time-picker>
        </el-form-item>
        
        <el-form-item label="提醒频率" prop="frequency">
          <el-select 
            v-model="form.frequency" 
            placeholder="请选择提醒频率"
            @change="handleFrequencyChange"
            style="width: 100%">
            <el-option label="每天" value="daily"></el-option>
            <el-option label="每周" value="weekly"></el-option>
            <el-option label="每月" value="monthly"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="星期几" prop="weekDays" v-if="form.frequency === 'weekly'">
          <el-select 
            v-model="form.weekDays" 
            multiple 
            placeholder="请选择星期几"
            style="width: 100%">
            <el-option label="星期一" value="1"></el-option>
            <el-option label="星期二" value="2"></el-option>
            <el-option label="星期三" value="3"></el-option>
            <el-option label="星期四" value="4"></el-option>
            <el-option label="星期五" value="5"></el-option>
            <el-option label="星期六" value="6"></el-option>
            <el-option label="星期日" value="7"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="每月几号" prop="monthDays" v-if="form.frequency === 'monthly'">
          <el-select 
            v-model="form.monthDays" 
            multiple 
            placeholder="请选择每月几号"
            style="width: 100%">
            <el-option 
              v-for="day in 31" 
              :key="day" 
              :label="`${day}号`" 
              :value="String(day)">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="激活状态" prop="isActive">
          <el-switch
            v-model="form.isActive"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const formRef = ref(null)

// 获取当前用户ID
let userId = null
const userInfoStr = localStorage.getItem('userInfo')
const userStr = localStorage.getItem('user')

if (userInfoStr) {
  try {
    userId = JSON.parse(userInfoStr).id
    console.log('从userInfo获取到用户ID:', userId)
  } catch (e) {
    console.error('解析userInfo失败:', e)
  }
} else if (userStr) {
  try {
    userId = JSON.parse(userStr).id
    console.log('从user获取到用户ID:', userId)
  } catch (e) {
    console.error('解析user失败:', e)
  }
}

if (!userId) {
  // 如果都没有获取到，默认使用ID为8用于测试
  userId = 8
  console.log('未找到用户信息，使用默认ID:', userId)
}

// 提醒列表
const reminders = ref([])
const loading = ref(false)

// 健康类型列表
const healthTypes = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加健康提醒')
const submitting = ref(false)

// 表单数据
const form = reactive({
  id: null,
  userId: userId,
  typeId: '',
  reminderTime: '',
  frequency: 'daily',
  weekDays: [],
  monthDays: [],
  isActive: true
})

// 表单验证规则
const rules = {
  typeId: [{ required: true, message: '请选择健康数据类型', trigger: 'change' }],
  reminderTime: [{ required: true, message: '请选择提醒时间', trigger: 'change' }],
  frequency: [{ required: true, message: '请选择提醒频率', trigger: 'change' }],
  weekDays: [{ 
    required: true, 
    message: '请选择星期几', 
    trigger: 'change',
    validator: (rule, value, callback) => {
      if (form.frequency === 'weekly' && (!value || value.length === 0)) {
        callback(new Error('请选择星期几'))
      } else {
        callback()
      }
    }
  }],
  monthDays: [{ 
    required: true, 
    message: '请选择每月几号', 
    trigger: 'change',
    validator: (rule, value, callback) => {
      if (form.frequency === 'monthly' && (!value || value.length === 0)) {
        callback(new Error('请选择每月几号'))
      } else {
        callback()
      }
    }
  }]
}

// 获取健康提醒列表
const getReminders = async () => {
  if (!userId) return
  
  loading.value = true
  try {
    // 尝试从本地存储获取数据
    const localData = localStorage.getItem(`health_reminders_${userId}`)
    if (localData) {
      reminders.value = JSON.parse(localData)
      console.log('从本地存储加载健康提醒:', reminders.value)
    } else {
      // 加载演示数据
      loadDemoReminders()
      // 保存演示数据到本地存储
      localStorage.setItem(`health_reminders_${userId}`, JSON.stringify(reminders.value))
    }
  } catch (error) {
    console.error('获取健康提醒失败', error)
    // 接口异常，使用模拟数据
    loadDemoReminders()
    // 保存演示数据到本地存储
    localStorage.setItem(`health_reminders_${userId}`, JSON.stringify(reminders.value))
  } finally {
    loading.value = false
  }
}

// 加载演示提醒数据
const loadDemoReminders = () => {
  reminders.value = [
    {
      id: 1,
      userId: userId,
      typeId: 1,
      typeName: '血压(收缩压)',
      reminderTime: '08:00:00',
      frequency: 'daily',
      weekDays: null,
      monthDays: null,
      isActive: true,
      createTime: new Date().toISOString()
    },
    {
      id: 2,
      userId: userId,
      typeId: 4,
      typeName: '血糖(空腹)',
      reminderTime: '07:00:00',
      frequency: 'daily',
      weekDays: null,
      monthDays: null,
      isActive: true,
      createTime: new Date().toISOString()
    },
    {
      id: 3,
      userId: userId,
      typeId: 6,
      typeName: '体重',
      reminderTime: '20:00:00',
      frequency: 'weekly',
      weekDays: '1,4,7',
      monthDays: null,
      isActive: true,
      createTime: new Date().toISOString()
    }
  ]
}

// 获取健康记录类型
const getHealthTypes = async () => {
  try {
    // 尝试从本地存储获取数据
    const localData = localStorage.getItem('health_types')
    if (localData) {
      healthTypes.value = JSON.parse(localData)
      console.log('从本地存储加载健康类型:', healthTypes.value)
      return
    }
    
    // 使用模拟数据
    loadDemoTypes()
    
    // 保存演示数据到本地存储
    localStorage.setItem('health_types', JSON.stringify(healthTypes.value))
  } catch (error) {
    console.error('获取健康记录类型失败', error)
    // 加载演示数据
    loadDemoTypes()
    // 保存演示数据到本地存储
    localStorage.setItem('health_types', JSON.stringify(healthTypes.value))
  }
}

// 加载演示的健康类型数据
const loadDemoTypes = () => {
  healthTypes.value = [
    { id: 1, name: '血压(收缩压)', unit: 'mmHg', isNumeric: true, minValue: 60, maxValue: 180, icon: 'iconfont icon-blood-pressure' },
    { id: 2, name: '血压(舒张压)', unit: 'mmHg', isNumeric: true, minValue: 40, maxValue: 120, icon: 'iconfont icon-blood-pressure' },
    { id: 3, name: '心率', unit: '次/分钟', isNumeric: true, minValue: 40, maxValue: 200, icon: 'iconfont icon-heart-rate' },
    { id: 4, name: '血糖(空腹)', unit: 'mmol/L', isNumeric: true, minValue: 3.9, maxValue: 6.1, icon: 'iconfont icon-blood-glucose' },
    { id: 5, name: '血糖(餐后2小时)', unit: 'mmol/L', isNumeric: true, minValue: 3.9, maxValue: 7.8, icon: 'iconfont icon-blood-glucose' },
    { id: 6, name: '体重', unit: 'kg', isNumeric: true, minValue: 30, maxValue: 150, icon: 'iconfont icon-weight' },
    { id: 7, name: '体温', unit: '℃', isNumeric: true, minValue: 35, maxValue: 42, icon: 'iconfont icon-temperature' },
    { id: 8, name: '睡眠时间', unit: '小时', isNumeric: true, minValue: 0, maxValue: 24, icon: 'iconfont icon-sleep' },
    { id: 9, name: '用药记录', unit: '', isNumeric: false, minValue: null, maxValue: null, icon: 'iconfont icon-medication' },
    { id: 10, name: '饮食记录', unit: '', isNumeric: false, minValue: null, maxValue: null, icon: 'iconfont icon-diet' }
  ]
}

// 英文健康类型名称翻译为中文
const translateTypeName = (engName) => {
  const typeMap = {
    'Blood Pressure (Systolic)': '血压(收缩压)',
    'Blood Pressure (Diastolic)': '血压(舒张压)',
    'Heart Rate': '心率',
    'Blood Glucose (Fasting)': '血糖(空腹)',
    'Blood Glucose (2h Postprandial)': '血糖(餐后2小时)',
    'Weight': '体重',
    'Body Temperature': '体温',
    'Sleep Duration': '睡眠时间',
    'Medication Record': '用药记录',
    'Dietary Record': '饮食记录'
  }
  return typeMap[engName] || engName
}

// 英文健康类型描述翻译为中文
const translateTypeDescription = (engDesc) => {
  const descMap = {
    'Systolic blood pressure measurement': '收缩压测量',
    'Diastolic blood pressure measurement': '舒张压测量',
    'Heart rate measurement': '心率测量',
    'Fasting blood glucose level': '空腹血糖水平',
    'Blood glucose 2 hours after meal': '餐后2小时血糖水平',
    'Body weight measurement': '体重测量',
    'Body temperature measurement': '体温测量',
    'Hours of sleep per night': '每晚睡眠时间',
    'Daily medication intake records': '每日药物摄入记录',
    'Daily food intake records': '每日食物摄入记录'
  }
  return descMap[engDesc] || engDesc
}

// 格式化提醒频率显示
const formatFrequency = (reminder) => {
  if (reminder.frequency === 'daily') {
    return '每天'
  } else if (reminder.frequency === 'weekly') {
    if (!reminder.weekDays) return '每周'
    
    const weekMap = {
      '1': '周一',
      '2': '周二',
      '3': '周三',
      '4': '周四',
      '5': '周五',
      '6': '周六',
      '7': '周日'
    }
    
    return '每周' + reminder.weekDays.split(',').map(day => weekMap[day]).join('、')
  } else if (reminder.frequency === 'monthly') {
    if (!reminder.monthDays) return '每月'
    
    return '每月' + reminder.monthDays.split(',').map(day => day + '号').join('、')
  }
  return ''
}

// 频率变化处理
const handleFrequencyChange = () => {
  if (form.frequency === 'daily') {
    form.weekDays = []
    form.monthDays = []
  } else if (form.frequency === 'weekly') {
    form.monthDays = []
  } else if (form.frequency === 'monthly') {
    form.weekDays = []
  }
}

// 添加提醒
const handleAdd = () => {
  dialogTitle.value = '添加健康提醒'
  form.id = null
  form.userId = userId
  form.typeId = ''
  form.reminderTime = ''
  form.frequency = 'daily'
  form.weekDays = []
  form.monthDays = []
  form.isActive = true
  
  dialogVisible.value = true
}

// 编辑提醒
const handleEdit = (row) => {
  dialogTitle.value = '编辑健康提醒'
  form.id = row.id
  form.userId = row.userId
  form.typeId = row.typeId
  form.reminderTime = row.reminderTime
  form.frequency = row.frequency
  form.isActive = row.isActive
  
  if (row.frequency === 'weekly' && row.weekDays) {
    form.weekDays = row.weekDays.split(',')
  } else {
    form.weekDays = []
  }
  
  if (row.frequency === 'monthly' && row.monthDays) {
    form.monthDays = row.monthDays.split(',')
  } else {
    form.monthDays = []
  }
  
  dialogVisible.value = true
}

// 删除提醒
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除此提醒吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 从本地存储获取提醒列表
      let reminderList = []
      const localData = localStorage.getItem(`health_reminders_${userId}`)
      if (localData) {
        reminderList = JSON.parse(localData)
      }
      
      // 找到要删除的提醒索引
      const reminderIndex = reminderList.findIndex(item => item.id === row.id)
      if (reminderIndex >= 0) {
        // 删除提醒
        reminderList.splice(reminderIndex, 1)
        
        // 保存更新后的提醒列表
        localStorage.setItem(`health_reminders_${userId}`, JSON.stringify(reminderList))
        
        ElMessage.success('删除成功')
        getReminders()
      } else {
        ElMessage.error('提醒不存在')
      }
    } catch (error) {
      console.error('删除提醒失败', error)
      ElMessage.error('删除提醒失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    let weekDaysStr = null
    if (form.frequency === 'weekly' && form.weekDays && form.weekDays.length > 0) {
      weekDaysStr = form.weekDays.join(',')
    }
    
    let monthDaysStr = null
    if (form.frequency === 'monthly' && form.monthDays && form.monthDays.length > 0) {
      monthDaysStr = form.monthDays.join(',')
    }
    
    try {
      submitting.value = true
      
      // 从本地存储获取提醒列表
      let reminderList = []
      const localData = localStorage.getItem(`health_reminders_${userId}`)
      if (localData) {
        reminderList = JSON.parse(localData)
      }
      
      // 查找健康类型信息
      const healthType = healthTypes.value.find(t => t.id === form.typeId)
      
      if (form.id) {
        // 更新提醒
        const reminderIndex = reminderList.findIndex(item => item.id === form.id)
        if (reminderIndex >= 0) {
          reminderList[reminderIndex] = {
            ...form,
            typeName: healthType ? healthType.name : '未知类型',
            weekDays: weekDaysStr,
            monthDays: monthDaysStr,
            createTime: reminderList[reminderIndex].createTime
          }
        }
      } else {
        // 添加提醒
        const newReminder = {
          id: Date.now(), // 使用时间戳作为唯一ID
          userId: userId,
          typeId: form.typeId,
          typeName: healthType ? healthType.name : '未知类型',
          reminderTime: form.reminderTime,
          frequency: form.frequency,
          weekDays: weekDaysStr,
          monthDays: monthDaysStr,
          isActive: form.isActive,
          createTime: new Date().toISOString()
        }
        
        reminderList.push(newReminder)
      }
      
      // 保存到本地存储
      localStorage.setItem(`health_reminders_${userId}`, JSON.stringify(reminderList))
      
      ElMessage.success(form.id ? '更新成功' : '添加成功')
      dialogVisible.value = false
      getReminders()
    } catch (error) {
      console.error('保存提醒失败', error)
      ElMessage.error('保存提醒失败')
    } finally {
      submitting.value = false
    }
  })
}

// 切换提醒状态
const handleStatusChange = async (row, value) => {
  try {
    // 从本地存储获取提醒列表
    let reminderList = []
    const localData = localStorage.getItem(`health_reminders_${userId}`)
    if (localData) {
      reminderList = JSON.parse(localData)
    }
    
    // 找到要更新的提醒索引
    const reminderIndex = reminderList.findIndex(item => item.id === row.id)
    if (reminderIndex >= 0) {
      // 更新状态
      reminderList[reminderIndex].isActive = value
      
      // 保存更新后的提醒列表
      localStorage.setItem(`health_reminders_${userId}`, JSON.stringify(reminderList))
      
      ElMessage.success('状态更新成功')
    } else {
      ElMessage.error('提醒不存在')
      // 回滚UI状态
      row.isActive = !value
    }
  } catch (error) {
    console.error('更新提醒状态失败', error)
    ElMessage.error('更新提醒状态失败')
    // 回滚UI状态
    row.isActive = !value
  }
}

// 初始化
onMounted(() => {
  getHealthTypes()
  getReminders()
})
</script>

<style scoped>
.health-reminder-container {
  padding: 20px;
}

.health-reminder-title {
  margin-bottom: 30px;
  font-size: 24px;
  color: #333;
  font-weight: 500;
}

.button-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-select .el-select__tags) {
  overflow: auto;
  max-height: 80px;
}

@media screen and (max-width: 768px) {
  .health-reminder-container {
    padding: 10px;
  }
}
</style> 